/**
 * @file user.js
 * @description 用户管理后端API路由
 * @created 2024-06-12
 */

import express from 'express';
import mysql from 'mysql';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { dbConfig } from '../../config/database.js';

const router = express.Router();

// 创建数据库连接池
const pool = mysql.createPool(dbConfig);

/**
 * 生成随机密码
 * @param {number} length - 密码长度
 * @returns {string} 随机密码
 */
function generateRandomPassword(length = 8) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let password = '';
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    password += chars[randomIndex];
  }
  return password;
}

/**
 * 获取用户列表
 * @route GET /admin/user/list
 */
router.get('/user/list', async (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;
  const offset = (page - 1) * limit;
  const keyword = req.query.keyword || '';
  
  try {
    // 查询条件
    let whereClause = '';
    let queryParams = [];
    
    if (keyword) {
      whereClause = `WHERE u.username LIKE ? OR u.real_name LIKE ? OR u.email LIKE ?`;
      const likeKeyword = `%${keyword}%`;
      queryParams = [likeKeyword, likeKeyword, likeKeyword];
    }
    
    // 获取总记录数
    const countSql = `SELECT COUNT(*) as total FROM users u ${whereClause}`;
    
    pool.query(countSql, queryParams, (countErr, countResults) => {
      if (countErr) {
        console.error('获取用户总数失败:', countErr);
        return res.status(500).json({
          code: 500,
          message: '获取用户总数失败',
          error: countErr.message
        });
      }
      
      const total = countResults[0].total;
      
      // 获取用户列表数据，同时关联学院和班级信息
      const dataSql = `
        SELECT 
          u.user_id as id, u.username, u.real_name as realName, u.role, 
          u.email, u.phone, u.status, u.last_login as lastLogin,
          c.name as collegeName, cl.name as className,
          u.college_id as collegeId, u.class_id as classId,
          u.created_at as createdAt, u.updated_at as updatedAt
        FROM users u
        LEFT JOIN yzh_colleges c ON u.college_id = c.id
        LEFT JOIN yzh_classes cl ON u.class_id = cl.id
        ${whereClause}
        ORDER BY u.user_id DESC
        LIMIT ? OFFSET ?
      `;
      
      pool.query(dataSql, [...queryParams, limit, offset], (dataErr, users) => {
        if (dataErr) {
          console.error('获取用户列表失败:', dataErr);
          return res.status(500).json({
            code: 500,
            message: '获取用户列表失败',
            error: dataErr.message
          });
        }
        
        return res.json({
          code: 200,
          message: '获取用户列表成功',
          data: {
            list: users,
            total,
            page,
            limit
          }
        });
      });
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取用户列表失败',
      error: error.message
    });
  }
});

/**
 * 获取单个用户详情
 * @route GET /admin/user/:id
 */
router.get('/user/:userId', (req, res) => {
  const userId = req.params.userId;
  
  const sql = `
    SELECT 
      user_id, username, email, role, active,
      last_login, created_at, updated_at
    FROM users
    WHERE user_id = ?
  `;
  
  pool.query(sql, [userId], (err, results) => {
    if (err) {
      console.error('Error fetching user:', err);
      return res.status(500).json({ 
        status: 'error', 
        message: '获取用户详情失败' 
      });
    }
    
    if (results.length === 0) {
      return res.status(404).json({ 
        status: 'error', 
        message: '用户不存在' 
      });
    }
    
    const user = results[0];
    
    // 如果是院级管理员，查询关联的学院
    if (user.role === 'college_admin') {
      const collegeSql = `
        SELECT uc.college_id, c.name as college_name 
        FROM user_college uc
        JOIN yzh_colleges c ON uc.college_id = c.id
        WHERE uc.user_id = ?
      `;
      
      pool.query(collegeSql, [userId], (collegeErr, collegeResults) => {
        if (collegeErr) {
          console.error('Error fetching college info:', collegeErr);
        } else if (collegeResults.length > 0) {
          user.college_id = collegeResults[0].college_id;
          user.college_name = collegeResults[0].college_name;
        }
        
        res.json({
          status: 'success',
          data: user
        });
      });
    } else {
      res.json({
        status: 'success',
        data: user
      });
    }
  });
});

/**
 * 添加用户
 * @route POST /admin/user/add
 */
router.post('/user/add', async (req, res) => {
  try {
    const { 
      username, 
      password, 
      realName, 
      role, 
      email, 
      phone, 
      collegeId, 
      classId, 
      status = 1 
    } = req.body;
    
    // 验证必填字段
    if (!username || !password || !realName || !role) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数'
      });
    }
    
    // 检查用户名是否已存在
    pool.query(
      'SELECT user_id FROM users WHERE username = ?',
      [username],
      async (err, results) => {
        if (err) {
          console.error('检查用户名失败:', err);
          return res.status(500).json({
            code: 500,
            message: '检查用户名失败',
            error: err.message
          });
        }
        
        if (results.length > 0) {
          return res.status(400).json({
            code: 400,
            message: '用户名已存在'
          });
        }
        
        // 加密密码
        const saltRounds = 10;
        const hashedPassword = await bcrypt.hash(password, saltRounds);
        
        // 插入新用户
        const insertSql = `
          INSERT INTO users 
            (username, password, real_name, role, email, phone, college_id, class_id, status, created_at, updated_at) 
          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
        `;
        
        pool.query(
          insertSql,
          [username, hashedPassword, realName, role, email, phone, collegeId, classId, status],
          (err, result) => {
            if (err) {
              console.error('添加用户失败:', err);
              return res.status(500).json({
                code: 500,
                message: '添加用户失败',
                error: err.message
              });
            }
            
            // 如果是学院管理员，需要添加用户-学院关联记录
            if (role === 'college_admin' && collegeId) {
              const relationSql = `
                INSERT INTO user_college (user_id, college_id, create_time)
                VALUES (?, ?, NOW())
              `;
              
              pool.query(relationSql, [result.insertId, collegeId], (relErr) => {
                if (relErr) {
                  console.error('添加用户-学院关联失败:', relErr);
                  // 继续返回成功，因为用户已经创建
                }
              });
            }
            
            return res.json({
              code: 200,
              message: '添加用户成功',
              data: {
                id: result.insertId
              }
            });
          }
        );
      }
    );
  } catch (error) {
    console.error('添加用户失败:', error);
    return res.status(500).json({
      code: 500,
      message: '添加用户失败',
      error: error.message
    });
  }
});

/**
 * 更新用户
 * @route PUT /admin/user/update/:id
 */
router.put('/user/update/:userId', async (req, res) => {
  try {
    const userId = req.params.userId;
    const { 
      realName, 
      role, 
      email, 
      phone, 
      collegeId, 
      classId, 
      status 
    } = req.body;
    
    // 验证必填字段
    if (!realName || !role) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数'
      });
    }
    
    // 更新用户信息
    const updateSql = `
      UPDATE users SET 
        real_name = ?, 
        role = ?, 
        email = ?, 
        phone = ?, 
        college_id = ?, 
        class_id = ?, 
        status = ?,
        updated_at = NOW()
      WHERE user_id = ?
    `;
    
    pool.query(
      updateSql,
      [realName, role, email, phone, collegeId, classId, status, userId],
      (err, result) => {
        if (err) {
          console.error('更新用户失败:', err);
          return res.status(500).json({
            code: 500,
            message: '更新用户失败',
            error: err.message
          });
        }
        
        if (result.affectedRows === 0) {
          return res.status(404).json({
            code: 404,
            message: '用户不存在'
          });
        }
        
        // 如果是学院管理员，更新用户-学院关联
        if (role === 'college_admin' && collegeId) {
          // 先删除现有关联
          pool.query('DELETE FROM user_college WHERE user_id = ?', [userId], (delErr) => {
            if (delErr) {
              console.error('删除用户-学院关联失败:', delErr);
            }
            
            // 添加新关联
            const relationSql = `
              INSERT INTO user_college (user_id, college_id, create_time)
              VALUES (?, ?, NOW())
            `;
            
            pool.query(relationSql, [userId, collegeId], (relErr) => {
              if (relErr) {
                console.error('更新用户-学院关联失败:', relErr);
              }
            });
          });
        } else if (role !== 'college_admin') {
          // 如果不是学院管理员，删除所有学院关联
          pool.query('DELETE FROM user_college WHERE user_id = ?', [userId], (delErr) => {
            if (delErr) {
              console.error('删除用户-学院关联失败:', delErr);
            }
          });
        }
        
        return res.json({
          code: 200,
          message: '更新用户成功'
        });
      }
    );
  } catch (error) {
    console.error('更新用户失败:', error);
    return res.status(500).json({
      code: 500,
      message: '更新用户失败',
      error: error.message
    });
  }
});

/**
 * 更新用户状态
 * @route PUT /admin/user/toggle-status/:id
 */
router.put('/user/toggle-status/:userId', (req, res) => {
  const userId = req.params.userId;
  const { status } = req.body;
  
  if (status === undefined) {
    return res.status(400).json({ 
      code: 400, 
      message: '状态参数不能为空' 
    });
  }
  
  // 检查是否为校级管理员（school_admin不允许禁用）
  pool.query('SELECT role FROM users WHERE user_id = ?', [userId], (checkErr, checkResults) => {
    if (checkErr) {
      console.error('检查用户角色失败:', checkErr);
      return res.status(500).json({
        code: 500,
        message: '检查用户角色失败',
        error: checkErr.message
      });
    }
    
    if (checkResults.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }
    
    if (checkResults[0].role === 'school_admin' && status === 0) {
      return res.status(403).json({
        code: 403,
        message: '不允许禁用校级管理员账户'
      });
    }
    
    // 更新状态
    pool.query(
      'UPDATE users SET status = ?, updated_at = NOW() WHERE user_id = ?',
      [status, userId],
      (err, result) => {
        if (err) {
          console.error('更新用户状态失败:', err);
          return res.status(500).json({
            code: 500,
            message: '更新用户状态失败',
            error: err.message
          });
        }
        
        return res.json({
          code: 200,
          message: `用户状态已${status === 1 ? '启用' : '禁用'}`
        });
      }
    );
  });
});

/**
 * 重置用户密码
 * @route POST /admin/user/reset-password/:id
 */
router.post('/user/reset-password/:userId', async (req, res) => {
  const userId = req.params.userId;
  
  try {
    // 默认密码
    const defaultPassword = '123456';
    
    // 加密密码
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(defaultPassword, saltRounds);
    
    // 更新密码
    pool.query(
      'UPDATE users SET password = ?, updated_at = NOW() WHERE user_id = ?',
      [hashedPassword, userId],
      (err, result) => {
        if (err) {
          console.error('重置密码失败:', err);
          return res.status(500).json({
            code: 500,
            message: '重置密码失败',
            error: err.message
          });
        }
        
        if (result.affectedRows === 0) {
          return res.status(404).json({
            code: 404,
            message: '用户不存在'
          });
        }
        
        return res.json({
          code: 200,
          message: '密码重置成功',
          data: {
            defaultPassword
          }
        });
      }
    );
  } catch (error) {
    console.error('重置密码失败:', error);
    return res.status(500).json({
      code: 500,
      message: '重置密码失败',
      error: error.message
    });
  }
});

/**
 * 删除用户
 * @route DELETE /admin/user/delete/:id
 */
router.delete('/user/delete/:userId', (req, res) => {
  const userId = req.params.userId;
  
  // 检查是否为校级管理员（school_admin不允许删除）
  pool.query('SELECT role FROM users WHERE user_id = ?', [userId], (checkErr, checkResults) => {
    if (checkErr) {
      console.error('检查用户角色失败:', checkErr);
      return res.status(500).json({
        code: 500,
        message: '检查用户角色失败',
        error: checkErr.message
      });
    }
    
    if (checkResults.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }
    
    if (checkResults[0].role === 'school_admin') {
      return res.status(403).json({
        code: 403,
        message: '不允许删除校级管理员账户'
      });
    }
    
    // 先删除用户-学院关联
    pool.query('DELETE FROM user_college WHERE user_id = ?', [userId], (relErr) => {
      if (relErr) {
        console.error('删除用户-学院关联失败:', relErr);
        // 继续删除用户
      }
      
      // 删除用户
      pool.query('DELETE FROM users WHERE user_id = ?', [userId], (err, result) => {
        if (err) {
          console.error('删除用户失败:', err);
          return res.status(500).json({
            code: 500,
            message: '删除用户失败',
            error: err.message
          });
        }
        
        if (result.affectedRows === 0) {
          return res.status(404).json({
            code: 404,
            message: '用户不存在'
          });
        }
        
        return res.json({
          code: 200,
          message: '删除用户成功'
        });
      });
    });
  });
});

/**
 * 获取用户权限
 * @route GET /admin/user/permissions/:id
 */
router.get('/user/permissions/:userId', (req, res) => {
  const userId = req.params.userId;
  
  // 先获取用户信息
  pool.query('SELECT role FROM users WHERE user_id = ?', [userId], (err, userResults) => {
    if (err) {
      console.error('Error fetching user role:', err);
      return res.status(500).json({ 
        status: 'error', 
        message: '获取用户信息失败' 
      });
    }
    
    if (userResults.length === 0) {
      return res.status(404).json({ 
        status: 'error', 
        message: '用户不存在' 
      });
    }
    
    const userRole = userResults[0].role;
    
    // 获取该角色的权限
    const permissionsSql = `
      SELECT 
        p.module, 
        GROUP_CONCAT(p.name) as actions
      FROM role_permissions rp
      JOIN permissions p ON rp.permission_id = p.id
      WHERE rp.role = ?
      GROUP BY p.module
    `;
    
    pool.query(permissionsSql, [userRole], (err, results) => {
      if (err) {
        console.error('Error fetching permissions:', err);
        return res.status(500).json({ 
          status: 'error', 
          message: '获取权限失败' 
        });
      }
      
      // 格式化权限数据
      const permissions = {
        role: userRole,
        modules: [],
        actions: {}
      };
      
      results.forEach(result => {
        permissions.modules.push(result.module);
        permissions.actions[result.module] = result.actions.split(',');
      });
      
      res.json({
        status: 'success',
        data: permissions
      });
    });
  });
});

export default router; 